import md5 from 'js-md5'

var all = {
    so: null,
    talk: {
        userData: { member_id: 0 }, //用户信息
        talkList: [], //会话列表
        chatRecord: [], //聊天记录
        journal: [], //日志
    },
    list: [{ title: "aa" }],
    post: {
        content: "",
        dialogueKey: "",
        thisTalkId: "",
    },
    /*onopen*/
    onopen: function (func) {
        // console.log("a");
        all.so.onopen = func;
    },
    /*onmessage*/
    onmessage: function (func) {
        all.so.onmessage = func;
    },
    /*onclose*/
    onclose: function (func) {
        all.so.onclose = func;
    },
    /*send*/
    send: function (content) {
        all.so.send(content);
    },
    /*getSoReadyState*/
    getSoReadyState: function () {
        return all.so.readyState;
    },
    /*testShow*/
    testShow: function (key) {
        console.log(key, this.talk[key]);
        return this.talk[key]
    },
    /*将信息发送给服务器*/
    sendMsg: function (sign, data) {
        if (sign != "login") {
            if (this.talk.userData.member_id == 0) {
                alert("请登录");
                return;
            }
        }
        var content = all.makeClientMsgPackage(sign, data, this.talk.userData.member_id);
        console.log(content);
        if (content.code != 200) {
            alert("程序错误");
            return;
        }
        console.log('发送信息', content.data)
        if (content.data.head.action == "对话") {
            this.addMsgToTalkDetail(content.data.body.talk_id, content.data.body, this.talk.userData.member_id);
        }
        this.talk.journal.push({ send: content.data, receipt: {} });
        this.so.send(JSON.stringify(content.data));
    },
    /*收到服务器发送信息的处理*/
    getServerSendMsg: function (data) {
        console.log('收到服务器发送消息', data);
        switch (data.head.action) {
            case "login":
                console.log("登录信息，可能是被踢下线");
            case "talk":
                console.log("对话", data);
                var sign = 0;
                for (var i = 0; i < this.talk.talkList.length; i++) {
                    if (this.talk.talkList[i].talk_id == data.body.talk_id) {
                        console.log('这')
                        sign = 1;
                        //将信息加入
                        this.talk.talkList[i]._child.push(data)
                    }
                }
                if (sign == 0) {
                    console.log('收到talk')
                    //取会话信息
                    this.talk.talkList.push({ talk_id: data.body.talk_id, _child: [data] });
                    this.sendMsg('method', { path: 'getTalkDetail', param: { talk_id: data.body.talk_id } });
                }
                break;
        }
    },
    /*收到服务器回执信息的处理*/
    getServerReceiptMsg: function (data) {
        var oneMsg = null;
        for (var i = 0; i < this.talk.journal.length; i++) {
            if (this.talk.journal[i].send.head.clientMsgId == data.head.clientMsgId) {
                this.talk.journal[i]["receipt"] = data;
                oneMsg = this.talk.journal[i];
            }
        }
        if (oneMsg == null) {
            if (data.body.code != 200) {
                console.log("非预期的信息", data);
            }
            return;
        }
        switch (oneMsg.send.head.action) {
            case "login":
                if (data.body.code != 200) {
                    alert(oneMsg.send.head.action + "失败，原因：" + data.body.data);
                    return;
                }
                this.talk["userData"] = data.body.data.userData;
                console.log("需要对历史记录处理", data.body.data.msgList);
                for (var i = 0; i < data.body.data.msgList; i++) {
                    this.getServerReceiptMsg(data.body.data.msgList[i]);
                }
                break;
            case "makeTemporaryTalk":
                if (data.body.code != 200) {
                    alert(oneMsg.send.head.action + "失败，原因：" + data.body.data);
                    return;
                }
                var sign = 0;
                for (var i = 0; i < this.talk["talkList"].length; i++) {
                    if (this.talk["talkList"][i]["talk_id"] == data.body.data.talk.id) {
                        sign = 1;
                        break;
                    }
                }
                if (sign == 0) {
                    data.body.data.talk["_child"] = [];
                    this.talk["talkList"].push(data.body.data.talk);
                    this.sendMsg("对话", { talk_id: data.body.data.talk.id, type: 1, content: data.body.data.title, });
                }
                break;
            case "method":
                if (data.body.code == 200) {
                    // console.log('method', data);
                    switch (data.body.path) {
                        case "getTalkDetail":
                            for (var i = 0; i < this.talk["talkList"].length; i++) {
                                if (this.talk["talkList"][i]["talk_id"] == data.body.data.id) {
                                    var talk = {
                                        talk_id: data.body.data.id, addTime: data.body.data.addTime, talkPartakeMemberIds: data.body.data.talkPartakeMemberIds,
                                        talkPartakeMembers: data.body.data.talkPartakeMembers, type: data.body.data.type, _child: this.talk["talkList"][i]['_child']
                                    };
                                    this.talk['talkList'][i] = talk;
                                    break;
                                }
                            }
                            break;
                        default:
                            alert('程序错误：收到错误的信息');
                            break;
                    }
                }
                break;
            case "talk":
                console.log('talk', data.body)
                if (data.body.code != 200) {
                    alert(oneMsg.send.head.action + "失败，原因：" + data.body.data);
                    return;
                }
                // console.log('talk的发送信息', oneMsg.send)
                for (var i = 0; i < this.talk["talkList"].length; i++) {
                    console.log(this.talk["talkList"][i]["talk_id"], oneMsg.send.body.talk_id)
                    if (this.talk["talkList"][i]["talk_id"] == oneMsg.send.body.talk_id) {
                        this.talk.talkList[i]['_child'].push(oneMsg.send);
                        break;
                    }
                }
                break;
        }
    },

    /*将聊天记录添加至会话*/
    addMsgToTalkDetail: function (talk_id, content, senMemberId) {
        for (var i = 0; i < this.talk["talkList"].length; i++) {
            if (this.talk["talkList"][i]["id"] == talk_id) {
                for (var h = 0; h < this.talk["talkList"][i]["talkPartakeMemberIds"].length; h++) {
                    if (this.talk["talkList"][i]["talkPartakeMemberIds"][h] == senMemberId) {
                        this.talk["talkList"][i]["_child"].push({ senMemberId: senMemberId, content: content });
                    }
                }
            }
        }
    },
    getSo: function (url, params) {
        let query = params
        if (all.so == null) {
            all.so = new WebSocket(url);
            all.so.onopen = function () {
                // console.log(query)
                if (all.so.readyState == 1) {
                    all.sendMsg("login", query)
                    // console.log(query)
                }
            };
            all.so.onclose = function () {
                //握手失败或者其他原因连接socket失败，则清除so对象并做相应提示操作
                all.so = false;
            };
            all.so.onmessage = function (msg) {
                //数据接收监听，接收服务器推送过来的信息，返回的数据给msg，然后进行显示
                var data = JSON.parse(msg.data);
                console.log("收到信息", data);
                if (data.head.ms == 1) {
                    //服务端发送的数据
                    all.getServerSendMsg(data);
                } else {
                    //服务端回执的数据
                    all.getServerReceiptMsg(data);
                }
                if (data.head.action == 'login') {
                    if (data.body.code = 200) {
                    }
                }
            };
        }
        return all;
    },
    makeClientMsgPackage: function (typeTitle, data, fromMemberId = 0) {
        var arr = [
            { type: "talk", keys: ["talk_id", "type", "content"] },                          //对话
            { type: "makeTemporaryTalk", keys: ["dialogueKey"] },                            //建立临时会话
            { type: "login", keys: ["key", "loginKey", "token", "sertype", "isForceLogin"], },  //登录
            { type: "method", keys: ["path", "param"] },

        ];
        var rigerMsg = null;
        var myDate = new Date();
        var outData = { head: { po: 2, ms: 1, fromMemberId: fromMemberId, clientMsgId: "", action: typeTitle, dateTime: myDate.toLocaleTimeString(), }, body: {}, };
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].type == typeTitle) {
                rigerMsg = arr[i];
                break;
            }
        }
        if (!rigerMsg) {
            return { data: "未注册信息类型", code: 301 };
        }
        for (var h = 0; h < rigerMsg.keys.length; h++) {
            var sign = 0;
            for (let key in data) {
                if (rigerMsg.keys[h] == key) {
                    sign = 1;
                    break;
                }
            }
            if (sign == 0) {
                return { data: "数据缺字段：" + rigerMsg.keys[h], code: 301 };
            }
        }
        for (var h = 0; h < rigerMsg.keys.length; h++) {
            var sign = 0;
            for (let key in data) {
                if (rigerMsg.keys[h] == key) {
                    outData["body"][key] = data[key];
                    break;
                }
            }
        }
        outData["head"]["clientMsgId"] = fromMemberId + "_" + md5(JSON.stringify(outData));
        return { data: outData, code: 200 };
    }
};


export default all